﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LeagueTableLibrary
{
    /// <summary>
    /// Klasa reprezentuje ligę wraz generowaniem harmonogramu spotkań.
    /// </summary>
    public class League
    {
        public int Id
        {
            get;
            private set;
        }

        private List<Team> _teams;

        /// <summary>
        /// Zbiór drużyn grających w lidze.
        /// </summary>
        public List<Team> Teams
        {
            get
            {
                if (_teams == null)
                    throw new NullReferenceException();
                else
                    return _teams;
            }

            set
            {
                if ((value.Count % 2) == 0)
                    this._teams = value;
            }
        }

        /// <summary>
        /// Zbiór kolejnych rund ligi.
        /// </summary>
        public List<Round> Rounds
        {
            get;
            private set;
        }

        /// <summary>
        /// Tworzy ligę o konkretnym indentyfikatorze.
        /// </summary>
        /// <param name="id">Identyfikator ligi.</param>
        public League(int id)
        {
            this._teams = new List<Team>();
            this.Rounds = new List<Round>();
            this.Id = id;
        }

        /// <summary>
        /// Tworzy harmonogram rozgrywek ligi z rewanżami wg tabeli Bergera.
        /// </summary>
        public void ComputeSchedule()
        {
            if (this.Teams == null)
                throw new NullReferenceException();

            int roundsNumber  = this.Teams.Count - 1;
            int matchesNumber = this.Teams.Count / 2;

            for (int r = roundsNumber; r <= roundsNumber * 2; r++)
            {
                Round r1 = new Round(r);
                Round r2 = new Round(r + roundsNumber);

                for(int m = 0; m <= matchesNumber; m++)
                {
                    Match currentMatch1 = new Match(
                        0, 
                        this.Teams[(r + m) % roundsNumber], 
                        this.Teams[(r - m) % roundsNumber]
                        );
                    Match currentMatch2 = new Match(
                        0,
                        this.Teams[(r - m) % roundsNumber],
                        this.Teams[(r + m) % roundsNumber]
                        );

                    r1.AddMatch(currentMatch1);
                    r2.AddMatch(currentMatch2);
                }
            }
        }
    }
}
